//
//  RHOtherFieldsDataVC.m
//  RuiHeAppApp
//
//  Created by Yan Chen on 2024/6/15.
//

#import "RHOtherFieldsDataVC.h"
#import "RHOtherFieldsCell.h"
@interface RHOtherFieldsDataVC ()<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic ,strong) UITableView *tableView;

@property (nonatomic, strong) RHDeviceModel *deviceModel;

@property (nonatomic, strong) RHEndPointModel *endpointModel;
@end

@implementation RHOtherFieldsDataVC
-(instancetype)initWithEndpointModel:(RHEndPointModel*)endpointModel deviceModel:(RHDeviceModel*)deviceModel
{
    if (self = [super init]) {
        _deviceModel = deviceModel;
        _endpointModel = endpointModel;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupUI];
}

-(void)setFormFields:(NSArray<DeviceChartFieldModel *> *)formFields{
    _formFields = formFields;
    [self getFormData];
}

-(void)setEmsEndpointModel:(RHEndPointModel *)emsEndpointModel
{
    _emsEndpointModel = emsEndpointModel;
    if (emsEndpointModel) {
        [self getEmsData];
    }
}

-(void)setMasterEndpointModel:(RHEndPointModel *)masterEndpointModel
{
    _masterEndpointModel = masterEndpointModel;
    if (masterEndpointModel) {
        [self getMasterData];
    }
}

-(void)setPcsEndpointModel:(RHEndPointModel *)pcsEndpointModel
{
    _pcsEndpointModel = pcsEndpointModel;
    if (pcsEndpointModel) {
        [self getPcsData];
    }
}

-(void)setLcuEndpointModel:(RHEndPointModel *)lcuEndpointModel
{
    _lcuEndpointModel = lcuEndpointModel;
    if (lcuEndpointModel) {
        [self getLcuData];
    }
}

-(void)setMeterEndpointModel:(RHEndPointModel *)meterEndpointModel
{
    _meterEndpointModel = meterEndpointModel;
    if (meterEndpointModel) {
        [self getMeterData];
    }
}

-(void)setDehumEndpointModel:(RHEndPointModel *)dehumEndpointModel
{
    _dehumEndpointModel = dehumEndpointModel;
    if (dehumEndpointModel) {
        [self getDehumData];
    }
}

-(void)setupUI
{
    _tableView = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStylePlain];
    _tableView.backgroundColor = CFTabViewBgColor;
    _tableView.delegate = self;
    _tableView.dataSource = self;
    [_tableView registerClass:[RHOtherFieldsCell class] forCellReuseIdentifier:@"RHOtherFieldsCell"];
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _tableView.tableHeaderView = [self headerView];
    _tableView.tableFooterView = [self footerView];
    [self.view addSubview:_tableView];
    _tableView.contentInset = UIEdgeInsetsMake(0, 0, 0, 0);

    
    [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.insets(UIEdgeInsetsZero);
    }];
    
    kWeakSelf;
    [_tableView addHeaderRefresh:^{
        [weakSelf getFormData];
        if (weakSelf.emsEndpointModel) {
            [weakSelf getEmsData];
        }
        if (weakSelf.masterEndpointModel) {
            [weakSelf getMasterData];
        }
        if (weakSelf.pcsEndpointModel) {
            [weakSelf getPcsData];
        }
        if (weakSelf.meterEndpointModel) {
            [weakSelf getMeterData];
        }
        if (weakSelf.lcuEndpointModel) {
            [weakSelf getLcuData];
        }
        if (weakSelf.dehumEndpointModel) {
            [weakSelf getDehumData];
        }

    }];
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.formFields.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    DeviceChartFieldModel *fieldModel = self.formFields[indexPath.row];
    RHOtherFieldsCell *cell = [tableView dequeueReusableCellWithIdentifier:@"RHOtherFieldsCell"];
    [cell setModel:fieldModel deviceTypeCode:self.deviceModel.deviceTypeCode];
    cell.line.hidden = (indexPath.row == (self.formFields.count -1));
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    [cell.bgView setMiddleBorder];
    return cell;
}

#pragma mark ---------------  获取 数据点 数据 ----

- (void)getFormData{
    
    if(self.formFields.count == 0){
        [self.tableView endHeaderRefresh];
        return;
    }
    NSMutableArray *paraKey = [NSMutableArray array];
    NSString *prefixKey = [NSString getEndpointParaPrefixStringWithEndpointCode:self.endpointModel.endpointCode deviceTypeCode:self.deviceModel.deviceTypeCode];
    //这里只获取当前端点的数据点
 
    [self.formFields enumerateObjectsUsingBlock:^(DeviceChartFieldModel*  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if (prefixKey.length>0) {

            if (obj.keyCode&&[obj.keyCode hasPrefix:prefixKey]) {
               
                //参数信息中有一些是相乘的参数,如 Emu_MaxChgCur*Emu_TV(允许最大充电功率)
                if([obj.keyCode containsString:@"*"]){
                    NSArray *keys = [obj.keyCode componentsSeparatedByString:@"*"];
                    if (keys.firstObject && ![paraKey containsObject:keys.firstObject]) {
                        [paraKey addObject:keys.firstObject];
                    }
                    if (keys.lastObject && ![paraKey containsObject:keys.lastObject]) {
                        [paraKey addObject:keys.lastObject];
                    }
                }else{

                    if ([obj.keyCode hasPrefix:prefixKey]) {
                        [paraKey addObject:obj.keyCode];
                    }
                }
            }

        }else{
            //参数中跟当前端点一致的才调接口,不然获取到的值是0
//            if (obj.keyCode) {
//                [paraKey addObject:obj.keyCode];
//            }
        }
        
    }];
    if (paraKey.count == 0) return;
    NSDictionary *paraDic =  @{@"deviceId":SafeStr(self.deviceModel.deviceId),
                                             @"endpointTypeCode":SafeStr(self.endpointModel.endpointCode),
                                             @"keyCodes":paraKey,
                                             @"endpointSn":SafeStr(self.endpointModel.sn)
                      };
    
    [QMUITips showLoadingInView:self.view];
    [BaseModel startWithCompletionAPIKey:D_getLastEndpointData argument:paraDic requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        [self.tableView endHeaderRefresh];
        if(resultModel.code == 200){
            if([request.responseObject[@"data"] isKindOfClass:[NSDictionary class]]){
                NSDictionary *dic = request.responseObject[@"data"];
                //对其他样式参数赋值
               
                [self.formFields enumerateObjectsUsingBlock:^(DeviceChartFieldModel*  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                    if (dic[obj.keyCode]) {
                        obj.content = dic[obj.keyCode];
                    }
                    //对于Emu_MaxChgCur*Emu_TV字段的赋值
                    if([obj.keyCode containsString:@"*"]){
                        NSArray *keys = [obj.keyCode componentsSeparatedByString:@"*"];
                        NSString *key1 = [keys firstObject];
                        NSString *key2 = [keys lastObject];
                        if (dic[key1]&&dic[key2]) {
                            double value = [dic[key1] doubleValue] * [dic[key2] doubleValue];
                            obj.content = [NSDecimalNumber decimalStringWithDouble:value];
                        }
                       
                    }
                }];
              
                [self.tableView reloadData];
            }
        }
        
        
    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        [self.tableView endHeaderRefresh];
    }];
}

- (void)getEmsData{
    
    NSMutableArray *paraKey = [NSMutableArray array];
   
    //pcs的参数点
 
    [self.formFields enumerateObjectsUsingBlock:^(DeviceChartFieldModel*  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if ([obj.keyCode.uppercaseString hasPrefix:@"EMS"]) {
            [paraKey addObject:obj.keyCode];
        }
    }];
    if (paraKey.count == 0) return;
    NSDictionary *paraDic =  @{@"deviceId":SafeStr(self.deviceModel.deviceId),
                               @"endpointTypeCode":SafeStr(self.emsEndpointModel.endpointCode),
                                             @"keyCodes":paraKey,
                               @"endpointSn":SafeStr(self.emsEndpointModel.sn)
                      };
    
    [BaseModel startWithCompletionAPIKey:D_getLastEndpointData argument:paraDic requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        [self.tableView endHeaderRefresh];
        if(resultModel.code == 200){
            if([request.responseObject[@"data"] isKindOfClass:[NSDictionary class]]){
                NSDictionary *dic = request.responseObject[@"data"];
               
                [self.formFields enumerateObjectsUsingBlock:^(DeviceChartFieldModel*  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                    if (dic[obj.keyCode]) {
                        obj.content = dic[obj.keyCode];
                    }
                }];
              
                [self.tableView reloadData];
            }
        }
        
        
    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        [self.tableView endHeaderRefresh];
    }];
}

- (void)getMasterData{
    
    NSMutableArray *paraKey = [NSMutableArray array];
   
    //pcs的参数点
 
    [self.formFields enumerateObjectsUsingBlock:^(DeviceChartFieldModel*  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if ([obj.keyCode hasPrefix:@"Mtr"]) {
            [paraKey addObject:obj.keyCode];
        }
    }];
    if (paraKey.count == 0) return;
    NSDictionary *paraDic =  @{@"deviceId":SafeStr(self.deviceModel.deviceId),
                               @"endpointTypeCode":SafeStr(self.masterEndpointModel.endpointCode),
                                             @"keyCodes":paraKey,
                               @"endpointSn":SafeStr(self.masterEndpointModel.sn)
                      };
    
    [BaseModel startWithCompletionAPIKey:D_getLastEndpointData argument:paraDic requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        [self.tableView endHeaderRefresh];
        if(resultModel.code == 200){
            if([request.responseObject[@"data"] isKindOfClass:[NSDictionary class]]){
                NSDictionary *dic = request.responseObject[@"data"];
               
                [self.formFields enumerateObjectsUsingBlock:^(DeviceChartFieldModel*  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                    if (dic[obj.keyCode]) {
                        obj.content = dic[obj.keyCode];
                    }
                }];
              
                [self.tableView reloadData];
            }
        }
        
        
    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        [self.tableView endHeaderRefresh];
    }];
}

- (void)getPcsData{
    
    NSMutableArray *paraKey = [NSMutableArray array];
   
    //pcs的参数点
 
    [self.formFields enumerateObjectsUsingBlock:^(DeviceChartFieldModel*  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if ([obj.keyCode hasPrefix:@"Pcs"]) {
            [paraKey addObject:obj.keyCode];
        }
    }];
    if (paraKey.count == 0) return;
    NSDictionary *paraDic =  @{@"deviceId":SafeStr(self.deviceModel.deviceId),
                                             @"endpointTypeCode":SafeStr(self.pcsEndpointModel.endpointCode),
                                             @"keyCodes":paraKey,
                                             @"endpointSn":SafeStr(self.pcsEndpointModel.sn)
                      };
    
    [BaseModel startWithCompletionAPIKey:D_getLastEndpointData argument:paraDic requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        [self.tableView endHeaderRefresh];
        if(resultModel.code == 200){
            if([request.responseObject[@"data"] isKindOfClass:[NSDictionary class]]){
                NSDictionary *dic = request.responseObject[@"data"];
               
                [self.formFields enumerateObjectsUsingBlock:^(DeviceChartFieldModel*  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                    if (dic[obj.keyCode]) {
                        obj.content = dic[obj.keyCode];
                    }
                }];
              
                [self.tableView reloadData];
            }
        }
        
        
    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        [self.tableView endHeaderRefresh];
    }];
}

- (void)getMeterData{
    
    NSMutableArray *paraKey = [NSMutableArray array];
   
    //meter的参数点
 
    [self.formFields enumerateObjectsUsingBlock:^(DeviceChartFieldModel*  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if ([obj.keyCode hasPrefix:@"GrSmmtr_"]) {
            [paraKey addObject:obj.keyCode];
        }
    }];
    if (paraKey.count == 0) return;
    NSDictionary *paraDic =  @{@"deviceId":SafeStr(self.deviceModel.deviceId),
                                             @"endpointTypeCode":SafeStr(self.meterEndpointModel.endpointCode),
                                             @"keyCodes":paraKey,
                                             @"endpointSn":SafeStr(self.meterEndpointModel.sn)
                      };
    
    [BaseModel startWithCompletionAPIKey:D_getLastEndpointData argument:paraDic requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        [self.tableView endHeaderRefresh];
        if(resultModel.code == 200){
            if([request.responseObject[@"data"] isKindOfClass:[NSDictionary class]]){
                NSDictionary *dic = request.responseObject[@"data"];
               
                [self.formFields enumerateObjectsUsingBlock:^(DeviceChartFieldModel*  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                    if (dic[obj.keyCode]) {
                        obj.content = dic[obj.keyCode];
                    }
                }];
              
                [self.tableView reloadData];
            }
        }
        
        
    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        [self.tableView endHeaderRefresh];
    }];
}

- (void)getLcuData{
    
    NSMutableArray *paraKey = [NSMutableArray array];
   
    //meter的参数点
 
    [self.formFields enumerateObjectsUsingBlock:^(DeviceChartFieldModel*  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if ([obj.keyCode hasPrefix:@"Lci_"]) {
            [paraKey addObject:obj.keyCode];
        }
    }];
    if (paraKey.count == 0) return;
    NSDictionary *paraDic =  @{@"deviceId":SafeStr(self.deviceModel.deviceId),
                                             @"endpointTypeCode":SafeStr(self.lcuEndpointModel.endpointCode),
                                             @"keyCodes":paraKey,
                                             @"endpointSn":SafeStr(self.lcuEndpointModel.sn)
                      };
    
    [BaseModel startWithCompletionAPIKey:D_getLastEndpointData argument:paraDic requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        [self.tableView endHeaderRefresh];
        if(resultModel.code == 200){
            if([request.responseObject[@"data"] isKindOfClass:[NSDictionary class]]){
                NSDictionary *dic = request.responseObject[@"data"];
               
                [self.formFields enumerateObjectsUsingBlock:^(DeviceChartFieldModel*  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                    if (dic[obj.keyCode]) {
                        obj.content = dic[obj.keyCode];
                    }
                }];
              
                [self.tableView reloadData];
            }
        }
        
        
    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        [self.tableView endHeaderRefresh];
    }];
}


- (void)getDehumData{
    
    NSMutableArray *paraKey = [NSMutableArray array];
   
    //meter的参数点
 
    [self.formFields enumerateObjectsUsingBlock:^(DeviceChartFieldModel*  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if ([obj.keyCode hasPrefix:@"dehum_"]) {
            [paraKey addObject:obj.keyCode];
        }
    }];
    if (paraKey.count == 0) return;
    NSDictionary *paraDic =  @{@"deviceId":SafeStr(self.deviceModel.deviceId),
                                             @"endpointTypeCode":SafeStr(self.dehumEndpointModel.endpointCode),
                                             @"keyCodes":paraKey,
                                             @"endpointSn":SafeStr(self.dehumEndpointModel.sn)
                      };
    
    [BaseModel startWithCompletionAPIKey:D_getLastEndpointData argument:paraDic requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        [self.tableView endHeaderRefresh];
        if(resultModel.code == 200){
            if([request.responseObject[@"data"] isKindOfClass:[NSDictionary class]]){
                NSDictionary *dic = request.responseObject[@"data"];
               
                [self.formFields enumerateObjectsUsingBlock:^(DeviceChartFieldModel*  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                    if (dic[obj.keyCode]) {
                        obj.content = dic[obj.keyCode];
                    }
                }];
              
                [self.tableView reloadData];
            }
        }
        
        
    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        [self.tableView endHeaderRefresh];
    }];
}



-(UIView*)headerView{
    UIView *header = kView;
    header.frame = CGRectMake(0, 0, kUI_WINDOW_W, 25);
    UIView *bgView = [[UIView alloc]initWithFrame:CGRectMake(15, 15, kUI_WINDOW_W-30, 10)];
    bgView.backgroundColor = UIColor.whiteColor;
    bgView.layer.cornerRadius = 8;
    [bgView setTopBorder];
    
    [header addSubview:bgView];
    return header;
}

-(UIView*)footerView{
    UIView *footer = kView;
    footer.frame = CGRectMake(0, 0, kUI_WINDOW_W, 20);
    UIView *bgView = [[UIView alloc]initWithFrame:CGRectMake(15, 0, kUI_WINDOW_W-30, 10)];
    bgView.backgroundColor = UIColor.whiteColor;
    bgView.layer.cornerRadius = 8;
    [bgView setBottomBorder];
    
    [footer addSubview:bgView];
    return footer;
}


@end
